package com.virtualparadigm.identity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class ResourcePathElement implements Serializable, Cloneable
{
	private static final long serialVersionUID = 1L;
	private static final String ELEMENT_DELIMITER = "_";
	
	private String name;
	private List<String> values;

	public ResourcePathElement(String name, List<String> elements)
	{
		super();
		this.name = name;
		this.values = elements;
	}
	public ResourcePathElement(String name, String strElements)
	{
		super();
		this.name = name;
		if(strElements != null && strElements.length() > 0)
		{
			this.values = new ArrayList<String>();
			String[] tokens = strElements.trim().split(ELEMENT_DELIMITER);
			for(int i=0; i<tokens.length; i++)
			{
				this.values.add(tokens[i]);
			}
		}
	}

	public String getName()
	{
		return name;
	}
	public List<String> getValues()
	{
		return values;
	}
	
	public String getValuesString()
	{
		StringBuffer sb = new StringBuffer();
		for(int i=0; i<values.size(); i++)
		{
			sb.append(values.get(i) + ELEMENT_DELIMITER);
		}
		if(sb.length() > 0)
		{
			return sb.substring(0, sb.length()-1);
		}
		return "";
	}
	
	
	// ================================================
	// UTILITY METHODS
	// ================================================
	public int hashCode()
	{
		HashCodeBuilder builder = new HashCodeBuilder(17,31);
	    builder.append(this.getName());
	    builder.append(this.getValuesString());
	    return builder.toHashCode();		
	}
	
	public boolean equals(Object obj)
	{
		if (obj == null)
		{
			return false;
		}
		if (obj == this)
		{
			return true;
		}
		if (obj.getClass() != getClass())
		{
			return false;
		}
		ResourcePathElement that = (ResourcePathElement)obj;
		EqualsBuilder builder = new EqualsBuilder();
	    builder.append(this.getName(), that.getName());
	    builder.append(this.getValuesString(), that.getValuesString());
		return builder.isEquals();
	}
	
	public String toString()
	{
		return "(" + this.getName() + ":" + this.getValuesString() + ")";
	}
	
	@Override
	public Object clone() throws CloneNotSupportedException
	{
		ResourcePathElement cloned = (ResourcePathElement)super.clone();
		cloned.name = this.name;
		this.values = new ArrayList<String>();
		for(String element : this.values)
		{
			this.values.add(new String(element));
		}
		return cloned;
	}
	
}